<?php
# !!!!!!!!!! DON'T MAKE ANY CHANGE IF YOU DON'T KNOW WHAT YOU'RE DOING !!!!!!!!!!
// --------------------------------------------------------------------------------------------------------------
// File Name              :	campaign.php
// Last Modification Time	:	2008-02-01 24:00
// Last Modified by       :	turker (turker.biz@gmail.com)
// list of modifications  :
//
//	- 2008-02-01 turker
//		* 24:00 file created.
//
// --------------------------------------------------------------------------------------------------------------
########################################## KAMPANYA MODÜLÜ ######################################################
#
# Bir ürün alındığında başka ürüne indirim uygulanabilmesi için kullanılır.
#
# Kullanmaya başlamadan önce aşağıdaki SQL kodunu kullanarak gerekli tabloyu oluşturun!
#
# CREATE TABLE `campaign` (
#   `id` int(10) unsigned NOT NULL auto_increment,
#   `main_item` int(10) unsigned NOT NULL,
#   `campaign_item` int(10) unsigned NOT NULL,
#   `discount_type` enum('ratio','rebate') NOT NULL,
#   `discount` varchar(10) NOT NULL,
#   `info` varchar(255) NOT NULL,
#   `date` varchar(10) NOT NULL,
#   `active` char(1) NOT NULL,
#   PRIMARY KEY  (`id`)
# ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
#
########################################## KAMPANYA MODÜLÜ ######################################################

if (eregi("campaign.php",$_SERVER['PHP_SELF'])) {
	header ("Location:../index.php");
	exit;
}

class Campaign {
  var $active=1; # kampanya özelliğini aktif/pasif etmek için, default: pasif
  var $maxInOne=5; # bir seferde, bir ürüne eklenebilecek max kampanya adedi.
  var $table='campaign'; # tablo adı

  function Campaign() {

  }

  function showCampaignAddBox() {
    $out='';
    if (count($_SESSION['campaigns'])<5) {
      $out='global $id;
      $checked="";
      if (in_array($id,$_SESSION["campaigns"])) $checked="checked";
      echo \'
      <script type="text/javascript">
      $(document).ready(function(){
        $("#campaignbox").click(function(){
          var check=$(this).attr("checked");
          var item=$(this).attr("name");
          if (check) check=1;
          else check=0;
          $.ajax({
          	data:"do=module&module=campaign&check="+check+"&item="+item,
          	success: function(r) {
              alert(r);
          	}
          });
        });
      });
      </script>
      <input type="checkbox" id="campaignbox" name="\'.$id.\'" value="1" \'.$checked.\' />
      Bu ürünü, başka bir ürüne kampanyalı olarak eklemek için seç.\';
      ';
    }
    return $out;
  }

  function showCampaignSaveForm() {
    global $ITEMS_TABLE;
    $max=$this->maxInOne;
    $out='global $mysql,$ITEMS_TABLE;
    $item=@(int)$_GET[\'item\'];
    echo \'<h1>Kampanya Ekle</h1><br />\';
    $campaigns=count($_SESSION[\'campaigns\']);
    if ($campaigns>0) {
      $campaigns=array();
      foreach ($_SESSION[\'campaigns\'] as $key=>$item_id) $campaigns[$key]="id=\'$item_id\'";
      $ids=implode(" or ",$campaigns);
      $q=$mysql->query("select item from $ITEMS_TABLE where ($ids)");

      echo \'<form method="post" action="index.php?page=module&module=campaign">\';
      echo \'<input type="hidden" name="item" value="\'.$item.\'" />\';
      echo \'<table width="100%" cellpadding="1" cellspacing="2">\';
      echo \'<tr><th align="center">Ürün</th><th align="center">Tür</th><th align="center">Miktar</th>\';
      echo \'<th align="center">Açıklama</th><th align="center">Sil</th>\';

      $i=0;
      foreach ($_SESSION[\'campaigns\'] as $key=>$val) {
        $title=$mysql->result($q,\'item\',$i);
        $id=trim($val);
        echo "<tr><td>$title</td>";
        echo \'<td align="center"><input type="radio" name="type[\'.$id.\']" value="ratio" checked /> Oran \';
        echo \'<input type="radio" name="type[\'.$id.\']" value="rebate" /> Miktar</td>\';
        echo \'<td align="center"><input type="text" name="discount[\'.$id.\']" /></td>\';
        echo \'<td align="center"><input type="text" name="info[\'.$id.\']" /></td>\';
        echo \'<td align="center"><input type="checkbox" name="del[\'.$id.\']" value="1" /></td></tr>\';
        if ($i=='.$max.') break;
        $i++;
      }
      echo \'<tr><td colspan="5" align="right"><input type="submit" value=" Kampanyayı Ekle " /></td><td></td></tr>\';
      echo "</table></form><br />";
    }
    else echo "Henüz Ürün Seçmemişsiniz.";';
    $out='$module=@htmlspecialchars($_GET[\'module\']);
    if ($module==\'campaign\') { '.$out.'}';
    return $out;
  }

  function saveCampaigns() {
    $table=$this->table;
    $out='global $mysql;
    extract($_POST,EXTR_OVERWRITE);

    $out=\'\';
    if (count($del)>0) {
      $out.=\'<br />Seçilen kampanya(lar) silindi.\';
      foreach ($del as $key=>$val) {
        unset($type[$key]);
        unset($discount[$key]);
        unset($info[$key]);
      }
    }

    if (count($type)>0) {
      $out.=\'<br />Seçilen kampanya(lar) eklendi.\';
      foreach ($type as $key=>$val) {
        $date=time();
        $t=$mysql->escape($val);
        $d=$mysql->escape($discount[$key]);
        $i=$mysql->escape($info[$key]);
        $a=1;
        $q=$mysql->query("insert into '.$table.' values (\'\',\'$item\',\'$key\',\'$t\',\'$d\',\'$i\',\'$date\',\'$a\')");
        if (!$q) {
          $out=\'Kampanya(lar) eklenemedi!\'.$mysql->mysqlRaiseError();
          break;
        }
      }
      unset($_SESSION[\'campaigns\']);
    }
    else unset($_SESSION[\'campaigns\']);

    echo \'<h1>Kampanya Ekle</h1><br />\'.$out;';
    $out='$module=@htmlspecialchars($_GET[\'module\']);
    if ($module==\'campaign\') { '.$out.'}';
    return $out;
  }

  function addToList() {
    $out='global $module,$item,$check;
    if ($module=="campaign"&&$item) {
      $item=(int)$item;
      if ($item<1) echo "Geçersiz işlem 1";
      else {
        if ($check==\'1\') {
          $_SESSION[\'campaigns\'][]=$item;
          echo "Ürün listeye eklendi.";
        }
        else {
          $key=array_search($item,$_SESSION[\'campaigns\']);
          unset($_SESSION[\'campaigns\'][$key]);
          echo "Ürün listeden çıkartıldı.";
        }
      }
    }';
    return $out;
  }

  function showAdminLink() {
    $out='global $out,$id;
    $key=array_search($id,$_SESSION[\'campaigns\']);
    if (count($_SESSION[\'campaigns\'])>0&&!is_numeric($key)) {
      $out.=\'|&nbsp;<a href="index.php?page=module&module=campaign&item=\'.$id.\'"/>Kampanya Ekle</a>\';
    }';
    return $out;
  }

  function showCampaigns() {
    global $SITE_SEO,$SITE_URL;
    $table=$this->table;
    $out='global $out,$id,$mysql;
    $q=$mysql->query("select * from '.$table.' where main_item=\'$id\' order by date asc");
    if ($mysql->numRows($q)>0) {
      $out.="<tr><td>";

      if (isAdmin()) {
        $out.=\'<script type="text/javascript">
        $(document).ready(function(){
          $("img[name=\\\'delCamp\\\']").each(function(){
            $(this).click(function(){
              if(confirm("Bu kampanyayı silmek istediğinize emin misiniz?")) {
                var id=$(this).attr("id");
                $.ajax({
                	data:"do=module&module=campaign&del="+id,
                	success: function(r) { eval(r); }
                });
            	}
            });
          });
        });
        </script>\';
      }

      while ($read=$mysql->fetch($q)) {
        $c_id=$read[\'id\'];
        $c_item=$read[\'campaign_item\'];
        $c_t=$read[\'discount_type\'];
        $c_d=htmlspecialchars($read[\'discount\']);
        $c_i=htmlspecialchars($read[\'info\']);

        $cItem=getItem($c_item);
        $cItemLink=\'<a href="index.php?page=item&id=\'.$c_item.\'">\'.htmlspecialchars($cItem[\'item\']).\'</a>\';
        if ('.$SITE_SEO.') $cItemLink=\'<a href="'.$SITE_URL.'/item/\'.$cItem[\'name\'].\'">\'.htmlspecialchars($cItem[\'item\']).\'</a>\';
        if (!empty($c_i)) $c_i="($c_i)";
        if ($c_t=="ratio") $c_t="%";
        else {
          $c_d=$c_d." TL";
          $c_t="";
        }

        $out.="<span id=\"citem$c_id\">";
        if (isAdmin()) { $out.=\'<img src="template/img/delete.gif" title="Kampanyayı Sil" name="delCamp" id="\'.$c_id.\'" class="imglist" /> \'; }
        $out.="$cItemLink ile birlikte alırsanız $c_t$c_d indirim! $c_i<br /></span>";
      }
      $out.="</td></tr>";
    }';
    return $out;
  }

  function delCampaign() {
    $table=$this->table;
    $out='global $module,$del,$mysql;
    if ($module=="campaign"&&$del) {
      $del=(int)$del;
      if ($del<1) echo "alert(\'Geçersiz işlem 1\');";
      else {
        $q=$mysql->query("delete from '.$table.' where id=\'$del\'");
        if (!$q) echo "alert(\'Hata! Daha sonra tekrar deneyin.\');";
        else {
          echo "alert(\'Kampanya silindi.\');";
          echo "$(\'#citem$del\').remove();";
        }
      }
    }';
    return $out;
  }

  function destructor() {
    return false;
  }
}

global $hook;
$Campaign=new Campaign();
//echo $Campaign->showCampaignAddBox('1');

if (isAdmin()) {
  $hook->addtoHook('itemAdmin',$Campaign->showCampaignAddBox());
  $hook->addtoHook('ajax',$Campaign->addToList());
  $hook->addtoHook('ajax',$Campaign->delCampaign());
  $hook->addtoHook('itemAdminLink',$Campaign->showAdminLink());
  $hook->addtoHook('modulePageBeforePost',$Campaign->showCampaignSaveForm());
  $hook->addtoHook('modulePageAfterPost',$Campaign->saveCampaigns());
  $hook->addtoHook('item',$Campaign->showCampaigns());
}

?>